<template>
  <div>
    <el-button type="primary" size="default" @click="handleDrawer(null)"
      >新增角色</el-button
    >
    <el-table :data="roleList" border stripe>
      <el-table-column prop="roleName" label="角色名称"> </el-table-column>
      <el-table-column label="角色权限">
        <template slot-scope="scope">
          <el-tag v-for="item in scope.row.permission" size="mini">{{
            routeMap[item]
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleDrawer(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="确定不是手抖了吗？"
            confirmButtonText="确认"
            cancelButtonText="取消"
            confirmButtonType="primary"
            cancelButtonType="text"
            icon="el-icon-question"
            iconColor="#f90"
            @confirm="handleDel(scope.row, scope.$index)"
          >
            <el-button slot="reference" type="danger" size="small"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer
      title="角色控制"
      :visible.sync="visible"
      direction="rtl"
      size="30%"
    >
      <RoleForm :row="rowData" v-if="visible" @update:table="handleTable" />
    </el-drawer>
  </div>
</template>

<script>
import { roleGet, roleDel } from "@/api/user";
import RoleForm from "./components/role-form.vue";
import { routeMapTool } from "@/utils/tools";
export default {
  components: {
    RoleForm,
  },
  data() {
    let routeMap = routeMapTool();
    return {
      roleList: [],
      visible: false,
      routeMap,
      rowData: null,
    };
  },
  created() {
    roleGet().then((res) => {
      this.roleList = res.data.results;
    });
  },
  methods: {
    handleDrawer(rowObj) {
      this.visible = true;
      //向表单组件传值
      this.rowData = rowObj;
    },
    //新增、编辑实时更新表格数据
    handleTable(obj) {
      let { roleList } = this;
      this.visible = false;
      console.log("子父通信", obj);
      for (let i = 0; i < roleList.length; i++) {
        if (roleList[i].objectId == obj.objectId) {
          roleList[i] = obj;
          this.roleList = [...roleList]; //解决对象引用问题
          return;
        }
      }
      roleList.push(obj); //新增角色
      this.roleList = [...roleList];
    },
    //删除角色
    handleDel({ objectId }, idx) {
      console.log(2222);
      roleDel(objectId).then((res) => {
        this.roleList.splice(idx, 1);
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
